package com.qs.controller;

import com.qs.util.R;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/api/file")
public class FileController {
    @PostMapping("/upload")
    public R<String> upload(@RequestParam("file") MultipartFile multipartFile) {
        String path = new ApplicationHome(getClass()).getSource().getParentFile() + "/upload/";
        String fileName = UUID.randomUUID() + "-NAME-" + multipartFile.getOriginalFilename();
        File file = new File(path, fileName);
        if (!file.getParentFile().exists()) {
            boolean mkdir = file.getParentFile().mkdir();
        }
        try {
            multipartFile.transferTo(file);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return R.ok(fileName);
    }
}
